#!/usr/bin/env python3
import sys
import getopt
import win32gui as w32g
import win32con as w32c

def print_usage():
    print('''Usage: listWindows [ls] [-h | --help]
    -h --help     show help
    -c --content  grep windows
    ls            show windows''')


title_list=[]

def foo(hwnd, mouse):
    titles = {}
    titles['title'] = w32g.GetWindowText(hwnd)
    titles['class'] = w32g.GetClassName(hwnd)
    titles['hwnd'] = hwnd
    if titles['title'] != '' and titles['title'] != 'Default IME' and titles['title'] != 'MSCTFIME UI':
        title_list.append(titles)

def show_windows(content):
    w32g.EnumWindows(foo, 0)
    print('Now Windows Num:', len(title_list))
    for title in title_list:
        if content in title['title']:
            print(title)


def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:'", ["help", "content=" ])
        if len(opts) == 0 and len(args) == 0:
            print_usage()
            sys.exit(0)
    except getopt.GetoptError:
        print_usage()
        sys.exit(-1)
    contentName = ''
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print_usage()
            return
        elif opt in ("-c", "--content"):
            contentName = arg
        else:
            return
    if contentName != '':
        show_windows(contentName)


if __name__ == "__main__":
    main()
    sys.exit(0)

